//
// Created by yeongguo(郭青云) on 2019-12-11.
//
#include "mp3_encode.h"

#include <android/log.h>
#include <math.h>


//短整型大小端互换
#define BigLittleSwap16(A) ((((uint16_t)(A) & 0xff00) >> 8 ) | \\


#define TAG "mp3_encode"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,TAG ,__VA_ARGS__) // 定义LOGI类型
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,TAG ,__VA_ARGS__) // 定义LOGW类型
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,TAG ,__VA_ARGS__) // 定义LOGE类型
#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,TAG ,__VA_ARGS__) // 定义LOGF类型

extern "C"

Mp3Encoder::Mp3Encoder() {

}

Mp3Encoder::~Mp3Encoder() {
}

int Mp3Encoder::lint(int sampleRate,
                     int channels,
                     int bitRate,
                     int quality) {
    LOGI("init lame, %d, %d, %d, %d", sampleRate, channels, bitRate, quality);
    int ret;
    lameClient = lame_init();
    lame_set_in_samplerate(lameClient, sampleRate);
    lame_set_num_channels(lameClient, channels);
    lame_set_brate(lameClient, bitRate);
    lame_set_quality(lameClient, quality);
    lame_init_params(lameClient);
    LOGI("lame init success");
    ret = 0;
    return ret;
}

EncodeData *Mp3Encoder::encode(
        const short *pcmData,
        long size) {
    int mp3_size = size;
    if (size < dataLength) {
        mp3_size = dataLength;
    }
    auto *encodeData = new EncodeData();
    auto *mp3_buffer = new unsigned char[mp3_size];
    int len1 = lame_encode_buffer(lameClient, pcmData, pcmData, size, mp3_buffer, mp3_size);
    if (len1 == -1) {
        LOGI("mp3数据太短，当前长度：%d", (int) size);
        len1 = 0;
    }
    encodeData->data = mp3_buffer;
    encodeData->length = len1;
    return encodeData;
}

int Mp3Encoder::Destroy() {
    lame_close(lameClient);
    LOGI("Destroy lame");
    return 0;
}
